
using Quartz;


namespace Movies.API.Extensions;


public static class QuartzJobAndTriggerExtension
{

    /// <summary>
    /// Add job and trigger 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="quartz"></param>
    /// <param name="configuration"></param>
    public static void AddJobAndTrigger<T>(this IServiceCollectionQuartzConfigurator quartz, IConfiguration configuration) where T : IJob
    {
        string jobName = typeof(T).Name;
        var option = GetCronJobOptions(configuration, jobName);
        if (!option.Enable) return;
        var jobKey = new JobKey(jobName);
        quartz.AddJob<T>(opts => opts.WithIdentity(jobKey));
        quartz.AddTrigger(opts => opts
            .ForJob(jobKey)
            .WithIdentity(jobName + "-trigger")
            .WithDescription("")
            .WithCronSchedule(option.Schedule!));
    }

    private static JobAndTriggerOption GetCronJobOptions(IConfiguration configuration, string jobName)
    {
        var quartzConfigSection = configuration.GetSection("Quartz") ?? throw new InvalidOperationException($"Quartz在appsettings.json未发现");
        var jobConfigSection = quartzConfigSection.GetSection(jobName) ?? throw new InvalidOperationException($"{jobName}在appsettings.json未发现"); ;
        var option = new JobAndTriggerOption();
        jobConfigSection.Bind(option);
        if (string.IsNullOrEmpty(option.Schedule)) throw new ArgumentException($"Job={jobName}的Schedule在appsettings.json未发现");
        return option;
    }
}





public class JobAndTriggerOption
{
    /// <summary>
    /// enable 
    /// </summary>
    public bool Enable { get; set; }
    /// <summary>
    /// corn expression 
    /// </summary>
    public string? Schedule { get; set; }
    /// <summary>
    /// Description
    /// </summary>
    public string? Description { get; set; }
}
